package user_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
)

type userPasswordRequest struct {
	OldPwd string `json:"old_pwd" binding:"required" msg:"请输入旧密码"`
	Pwd    string `json:"pwd" binding:"required" msg:"请输入新密码"`
}

// UserModifyPassword 前段用户修改自己的密码
func (UserApi) UserModifyPassword(c *gin.Context) {
	var cr userPasswordRequest
	if err := c.ShouldBindJSON(&cr); err != nil {
		http.FailWithError(err, &cr, c)
		return
	}

	// 获取 token 用户信息
	claims, _ := c.Get("user")
	user := claims.(*utils.UserClaims)
	// 检查是否存在用户
	var userInfo models.UserModel
	err := common.DB.Take(&userInfo, user.UserID).Error
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("用户不存在", c)
		return
	}
	// 判断旧密码是否正确
	if !utils.ComparePasswords(userInfo.Password, cr.OldPwd) {
		http.FailWithMessage("密码错误", c)
		return
	}
	// 判断两次修改密码是否一致
	if utils.ComparePasswords(userInfo.Password, cr.Pwd) {
		http.FailWithMessage("修改密码和旧密码一致", c)
		return
	}
	// 修改密码
	hashPwd, _ := utils.HashPwd(cr.Pwd)
	err = common.DB.Model(&userInfo).Update("password", hashPwd).Error
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("修改密码失败", c)
		return
	}
	http.IsOkWithMessage("修改成功", c)
}
